package com.ljm.boot.apilimit.controller;

import com.ljm.boot.apilimit.limit.RateLimit;
import com.ljm.boot.apilimit.limit.RedisRateLimit;
import com.ljm.boot.apilimit.limit.SemaphoreLimit;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author Dominick Li
 * @CreateTime 2020/5/2 10:41
 * @description
 **/
@RestController
public class LimitTestController {

    @Autowired
    private RedissonClient client;


    /**
     * 设置limitKey=ratelimitKey,并且每秒许可证只有3个
     */
    @RateLimit(limitKey = "ratelimitKey",value =3)
    @RequestMapping("/ratelimit")
    public String ratelimit() throws Exception{
        //假设业务处理了1秒
        TimeUnit.SECONDS.sleep(1);
        return "success";
    }

    /**
     * 设置limitKey=semaphoreKey,并且最多允许3个线程同时执行
     */
    @SemaphoreLimit(limitKey ="semaphoreKey", value =3)
    @RequestMapping("/semaphoreLimit")
    public String semaphoreLimit() throws Exception{
        //假设业务处理了1秒
        TimeUnit.SECONDS.sleep(1);
        return "success";
    }

    /**
     * 设置limitKey=redisRatelimit,并且每2秒许可证只有7个
     */
    @RedisRateLimit(limitKey = "redisRatelimit",value =7,time = 2)
    @RequestMapping("/redisRatelimit")
    public String redisRatelimit(){
        return "success";
    }

    @RequestMapping("/redisTestBloomFilter")
    public String redisTestBloomFilter(){
        try {
            String filterName = "myBloomFilter";
            long expectedInsertions = 1000L; // 预期元素数量
            double falseProbability = 0.01; // 容错率，也就是误报率

            // 创建布隆过滤器，参数分别为：过滤器名称，预期元素数量，误差率
            RBloomFilter<Object> bloomFilter = client.getBloomFilter(filterName);
            bloomFilter.tryInit(expectedInsertions, falseProbability);
            // 添加元素
            for (int i = 1; i <= 50; i++) {
                bloomFilter.add(String.format("element%02d", i));
            }

            // 检查元素是否存在
            System.out.println("bloomFilter.contains(\"element01\") = " + bloomFilter.contains("element01"));
            System.out.println("bloomFilter.contains(\"element51\") = " + bloomFilter.contains("element51"));
        } finally {
            // 关闭 Redission 客户端
            client.shutdown();
        }
        return "success";
    }
}
